<template>
  <div>
    <!-- //!二级分类数据筛选 -->
    <!-- {{$store.state.category}} -->
    <!-- {{breadobj}} -->
    <!-- //!面包屑 -->
    <BreadView>
      <BreadItem :to="'/'">首页</BreadItem>
      <BreadItem :to="`/cate?id=${breadobj.onecateid}`">{{breadobj.onecatename}}</BreadItem>
      <transition name="bounce">
        <BreadItem>{{breadobj.towcatename}}</BreadItem>
      </transition>
    </BreadView>
    <!-- //!属性展示区 -->
    <!-- 筛选区 -->
    <div class="sub-filter" v-if="brandattr">
      <div class="item">
        <div class="head">品牌：</div>
        <div class="body">
          <a href="javascript:;" :class="{active:item.id==brandid}" v-for="item in brandattr" :key="item.id" @click="setBrand(item.id)">{{item.name}}</a>
        </div>
      </div>
      <div class="item" v-for="item in attr" :key="item.id">
        <div class="head">{{item.name}}</div>
        <div class="body">
          <a href="javascript:;" :class="{active:changeattr[key]&&i.id==changeattr[key].id}" v-for="(i,key) in item.properties" :key="i.id" @click="setchangeattr(key,item.name,i.name,i.id)">{{i.name}}</a>
        </div>
      </div>
    </div>
    <div class="sub-filter" v-else>
      <SkeletonView width="800px" height="20px" />
      <SkeletonView width="700px" height="20px" />
      <SkeletonView width="600px" height="20px" />
      <SkeletonView width="800px" height="20px" />
      <SkeletonView width="700px" height="20px" />
    </div>
    <!-- //!排序展示区 -->
    <div class="goods-list">
      <!-- <SubSort /> -->

      <div class='sub-sort'>
        <!-- {{sortField}} -->
        <div class="sort">
          <a href="javascript:;" :class="{active:sortField===null}" @click="changeSort(null)">默认排序</a>
          <a href="javascript:;" :class="{active:sortField==='publishTime'}" @click="changeSort('publishTime')">最新商品</a>
          <a href="javascript:;" :class="{active:sortField==='orderNum'}" @click="changeSort('orderNum')">最高人气</a>
          <a href="javascript:;" :class="{active:sortField==='evaluateNum'}" @click="changeSort('evaluateNum')">评论最多</a>
          <a href="javascript:;" @click="changeSort('price')">
            价格排序
            <i class="arrow up" :class="{active:sortField==='price'&&sortMethod=='asc'}" />
            <i class="arrow down" :class="{active:sortField==='price'&&sortMethod=='desc'}" />
          </a>
        </div>
        <div class="check">
          <XtxCheckbox v-model="inventory" >仅显示有货商品</XtxCheckbox>
          <XtxCheckbox :val.sync="onlyDiscount" :title="'cheap'">仅显示特惠商品</XtxCheckbox>
        </div>
      </div>

      <!-- //!结果展示区 -->
      <ul>
        <GoodsItem v-for="item in goodslist" :key="item.id" :i="item"  @click.native="$router.push('/detail?id='+item.id)"/>
      </ul>
    </div>
    <XtxInfiniteLoading :finished="finished" :loading="loading" @getdata="getdata" />
  </div>
</template>

<script>
import BreadItem from "@/components/utils/Bread/BreadItem.vue";
import BreadView from "@/components/utils/Bread/BreadView.vue";
import { getFilter } from '@/utils/api/homeapi'
import SkeletonView from "../utils/SkeletonView.vue";
// import SubSort from "./SubSort.vue";
import GoodsItem from '../categroy/GoodsItem.vue'
import { getTop } from "@/utils/api/homeapi"
import XtxInfiniteLoading from "./XtxInfiniteLoading.vue"
import XtxCheckbox from './XtxChechbox.vue'
export default {
  components: { BreadView, BreadItem, SkeletonView, XtxInfiniteLoading, GoodsItem, XtxCheckbox },
  data() {
    return {
      breadobj: {
        towcatename: null,
        onecatename: null,
        onecateid: null
      },
      brandattr: null,
      attr: null,
      query: {
        categoryId: null,
        page: 1,
        pageSize: 20,
      },
      loading: false,  // 正在加载中
      finished: false, // 是否已经加载完成
      goodslist: [],
      inventory: false,
      onlyDiscount: false,
      sortField: null,
      sortMethod: null,
      brandid: null,// 当前选择的id
      changeattr: [],
    }
  },
  methods: {
    // 面包屑方法
    setBread() {
      for (var i = 0; i <= this.cate.length - 1; i++) {
        var index = this.cate[i].children.findIndex((item) => {
          // console.log(this.cate[i]);
          return item.id == this.$route.query.id;
        });
        if (index != -1) {
          //   console.log(i, index);
          // var obj = {}
          this.breadobj.towcatename = this.cate[i].children[index].name
          this.breadobj.onecatename = this.cate[i].name
          this.breadobj.onecateid = this.cate[i].id
          // this.$set(this.breadobj,'towcatename',obj.towcatename)
          //   console.log(this.breadobj);
          break;
        }
      }
    },
    // 筛选区的数据
    async getAttr(id) {
      let res = await getFilter(id)
      //   console.log(res);
      this.brandattr = res.result.brands
      // 需要给brandattr 在头部添加一个全部的空数据
      var obj = { id: null, name: '全部' }
      this.brandattr.unshift(obj)
      this.attr = res.result.saleProperties
      this.attr.forEach(item => {
        item.properties.unshift(obj)
      });
    },
    async getdata() {
      this.loading = true
      let res = await getTop(this.query)
      // console.log(res)
      if (res.result && res.result.items.length != 0) {
        // this.loading=false
        this.goodslist = [...this.goodslist, ...res.result.items]
        // console.log(this.goodslist)
        this.query.page += 1
        // this.loading=false
      } else {
        // 没拿到数据 以及完成
        this.finished = true
      }
      this.loading = false
    },
    changeSort(sortField) {
      if (sortField === 'price') {
        this.sortField = sortField
        if (this.sortMethod === null) {
          this.sortMethod = 'desc'
        } else {
          // 其他情况根据当前排序取反
          this.sortMethod = this.sortMethod === 'desc' ? 'asc' : 'desc'
        }
      } else {
        // 如果排序未改变停止逻辑  
        if (this.sortField === sortField) return
        this.sortField = sortField
        this.sortMethod = null
      }
    },
    // 设置品牌
    setBrand(id) {
      // 保存点击的id
      this.brandid = id
      // 请求数据
      this.query.page = 1
      this.query.brandId = id
      this.goodslist = []
      this.getdata()
      // console.log(this.query)
    },
    setchangeattr(key, onename, twoname, twoid) {
      // console.log(key,onename,twoname,twoid)
      var obj = { groupName: onename, propertyName: twoname, id: twoid }
      this.$set(this.changeattr, key, obj)
    },
    // 重置请求参数
    resetgetdata() {
      this.query.page = 1
      this.goodslist = []
      this.getdata()
    }
  },
  computed: {
    cate() {
      return this.$store.state.category.cate;
    },
  },
  mounted() {
    // let cate = this.$store.state.category.cate;
    // 调用属性获取的方法
    // this.getAttr(this.$route.query.id)
    this.query.categoryId = this.$route.query.id
    this.getdata(this.query)


  },
  watch: {
    '$route': {
      async handler(val) {
        if (val) {
          this.setBread()
          await this.getAttr(this.$route.query.id)
          // 设置选择的数组
          var obj = { groupName: null, propertyName: null, id: null }
          this.changeattr = []
          // 遍历attr数组
          for (var i = 0; i < this.attr.length; i++) {
            this.changeattr.push(obj)
          }
          //  console.log(this.changeattr)
        }
      },
      deep: true,
      immediate: true
    },
    sortField(val) {
      // handler(val) {
      // console.log(val)
      // 清空原来的数据
      //  this.goodslist = []
      // console.log(this.goodslist)
      // 重置第一页
      //  this.query.page = 1
      if (val == 'price') {
        this.query.sortField = val
        this.query.sortMethod = this.sortMethod
      } else {
        this.query.sortField = val
        this.query.sortMethod = null
      }
      // this.query = { ...this.query, sortField: this.sortField }
      //  this.getdata()
      this.resetgetdata()
      // this.query.sortMethod = null
    },
    changeattr(val) {
      // 过滤出id为null的数据不发送请求
      var attr = val.filter(item => {
        return item.id != null
      })
      // 链接this.query发请求
      this.query = { ...this.query, ...{ attr } }
      this.goodslist = []
      if (attr.length != 0) {
        this.getdata()
      }
    },
    // 价格监听
    sortMethod(val, oldval) {
      // 从desc 或者 asc 变成空的时候不发送请求
      // console.log(val,oldval)
      if (val == null) false
      //从空到desc的时候再前面已经法国请求  可以不发请求
      if (oldval != null) {
        this.query.sortMethod = val
        this.resetgetdata()
      }
    },
    // 有没有货
    onlyDiscount(val) {
      console.log(val)
      this.query.onlyDiscount = val
      this.resetgetdata()
    },
    deep: true,
    //  immediate: true
    //   }

  },
};
</script>

<style lang="scss" scoped>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
@import "@/assets/css/color.scss";
/* 可以设置不同的进入和离开动画 */
/* 设置持续时间和动画函数 */
.bounce-enter-active {
  animation: bounce-in 0.5s;
}
// .bounce-leave-active {
//   animation: bounce-in 0.5s reverse;
// }
@keyframes bounce-in {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.5);
  }
  100% {
    transform: scale(1);
  }
}
// 筛选区
.sub-filter {
  background: #fff;
  padding: 25px;
  .item {
    display: flex;
    line-height: 40px;
    .head {
      width: 80px;
      color: #999;
    }
    .body {
      flex: 1;
      a {
        margin-right: 36px;
        transition: all 0.3s;
        display: inline-block;
        &.active,
        &:hover {
          color: $xtxColor;
        }
      }
    }
  }
}
.active {
  color: $xtxColor;
}
.sub-sort {
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .sort {
    display: flex;
    a {
      height: 30px;
      line-height: 28px;
      border: 1px solid #e4e4e4;
      padding: 0 20px;
      margin-right: 20px;
      color: #999;
      border-radius: 2px;
      position: relative;
      transition: all 0.3s;
      &.active {
        background: $xtxColor;
        border-color: $xtxColor;
        color: #fff;
      }
      .arrow {
        position: absolute;
        border: 5px solid transparent;
        right: 8px;
        &.up {
          top: 3px;
          border-bottom-color: #bbb;
          &.active {
            border-bottom-color: $xtxColor;
          }
        }
        &.down {
          top: 15px;
          border-top-color: #bbb;
          &.active {
            border-top-color: $xtxColor;
          }
        }
      }
    }
  }
  .check {
    .xtx-checkbox {
      margin-left: 20px;
      color: #999;
    }
  }
}
</style>
